﻿using System;
using System.Windows;

using SBPweb.RIA.Client.Controls.Base;
using SBPweb.RIA.Client.Controls.Windows;

using SBPweb.PlAzureNet.Client.Library.Controllers;

using SBPweb.PlAzureNet.Client.Presenter.Pages;

namespace SBPweb.PlAzureNet.Client.Presenter
{

    public partial class App : ExtendableApplication
    {

        #region Fields

        private ErrorWindow errorWindow;
        private ModuleLoader moduleLoader;

        #endregion

        public App()
        {
            this.Startup += this.Application_Startup;
            this.Exit += this.Application_Exit;
            this.UnhandledException += this.Application_UnhandledException;

            InitializeComponent();
            IsSettingsPersistencyEnabled = true;
            IsLocalCachePersistencyEnabled = false;//!System.Diagnostics.Debugger.IsAttached;
        }

        private void Application_Startup(object sender, StartupEventArgs e)
        {
            System.Globalization.CultureInfo ci = new System.Globalization.CultureInfo("en-US");
            System.Threading.Thread.CurrentThread.CurrentCulture = ci;
            System.Threading.Thread.CurrentThread.CurrentUICulture = ci;

            RootVisual = new RootPage();
            moduleLoader = new ModuleLoader();
        }

        private void Application_Exit(object sender, EventArgs e)
        {

        }

        private void Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
        {
            RootVisual.Dispatcher.BeginInvoke(() =>
            {
                ShowErrorDialog(e);
            });
            e.Handled = true;
        }

        private void ShowErrorDialog(ApplicationUnhandledExceptionEventArgs e)
        {
            if (errorWindow == null)
            {
                errorWindow = new ErrorWindow("WindowsRootPanel", e.ExceptionObject);
            }
            else
            {
                errorWindow.SetUIContentBasedOnException(e.ExceptionObject);
            }
            errorWindow.OpenDialog();
        }

        private void ReportErrorToDOM(ApplicationUnhandledExceptionEventArgs e)
        {
            try
            {
                string errorMsg = e.ExceptionObject.Message + e.ExceptionObject.StackTrace;
                errorMsg = errorMsg.Replace('"', '\'').Replace("\r\n", @"\n");

                System.Windows.Browser.HtmlPage.Window.Eval("throw new Error(\"Unhandled Error in Silverlight Application " + errorMsg + "\");");
            }
            catch (Exception)
            {
            }
        }

    }

}